import React, { createContext, useContext, useState, useEffect } from "react";
import { useRouter } from "next/router";
import { useProducts } from "@/business.InterfaceLayer/hooks/store/useQueryStore/useQueryStore";
import { Product } from "@/business.InterfaceLayer/type";

export interface CategoryProviderProps {
  children: React.ReactNode;
}

export interface CategoryContextType {
  activeCategory: string;
  setActiveCategory: React.Dispatch<React.SetStateAction<string>>;
  activeRefinements: string[];
}

const CategoryContext = createContext<CategoryContextType>({
  activeCategory: "",
  setActiveCategory: () => {},
  activeRefinements: [],
});

export const CategoryProvider: React.FC<CategoryProviderProps> = ({
  children,
}) => {
  const router = useRouter();
  const { products } = useProducts();
  const [activeCategory, setActiveCategory] = useState("");
  const [activeRefinements, setActiveRefinements] = useState<string[]>([]);

  useEffect(() => {
    if (router.query && router.query.category) {
      setActiveCategory(router.query.category as string);
    }
  }, [router.query]);

  useEffect(() => {
    if (products.length > 0) {
      const refinements: string[] = Array.from(
        new Set(
          products
            .filter((product: Product) => product.category === activeCategory)
            .map((product: Product) => product.refinement)
        )
      );
      setActiveRefinements(refinements);
    }
  }, [products, activeCategory]);

  return (
    <CategoryContext.Provider
      value={{
        activeCategory,
        setActiveCategory,
        activeRefinements,
      }}
    >
      {children}
    </CategoryContext.Provider>
  );
};

export const useCategory = () => useContext(CategoryContext);
